/**
 *  JFTSTool - Java Full Text Search tool.
 *  Copyright (C) <2009>  <grupo JFTS>
 *  This program is free software: you can redistribute it and/or modify
 *	it under the terms of the GNU General Public License as published by
 *	the Free Software Foundation, either version 3 of the License, or
 *	(at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.jftstool.analyzers.filters;


import java.io.IOException;
import java.util.Stack;

import org.apache.lucene.analysis.Token;
import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.jftstool.synonymousEngine.ISynonymEngine;

/**
 * Filter charge of obtaining a word synonymous ed.
 * Receives as parameter an instance of ISynonymEngine, class <br>
 * that determines the final language of the filter.
 * @author grupo JFTS
 *
 */
public class SynonymousFilter extends TokenFilter{
	private ISynonymEngine engine = null;
	private Stack<Token> synonymStack;	
	public static final String TOKEN_TYPE_SYNONYM = "SYNONYM";
		

	
	public SynonymousFilter(TokenStream in, ISynonymEngine engine) {    
		super(in);    
		synonymStack = new Stack<Token>();		
		this.engine = engine;
	}
	

    public final Token next(final Token reusableToken) throws IOException {
    	assert reusableToken != null;
    	
    	if (synonymStack.size() > 0) {
    		return (Token) synonymStack.pop();
    	}
    	
		Token token = input.next(reusableToken);
		if (token == null) {
			return null;
		}    	
		_addSynonymsToStack(token);
    	return token;
    }
    
    private void _addSynonymsToStack(Token token) throws IOException {
    	String[] synonyms = engine.getSynonyms(token.term());
    	
    	if (synonyms == null){
    		return;
    	}
    	
    	char[] text = null;
    	for (int i = 0; i < synonyms.length; i++) {
    		text = synonyms[i].toCharArray();
    		Token synToken = new Token(text, 0, text.length, token.startOffset(), token.endOffset());
    		synToken.setType(TOKEN_TYPE_SYNONYM);
    		synToken.setPositionIncrement(0);
    		synonymStack.push(synToken);
    	}
    }    
    
}